<template>
  <el-dialog
    v-el-drag-dialog
    :title="!id ? '新增数据' : '修改数据'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="奖励类型" prop="prizeType" label-width="100px">
        <el-select v-model="dataForm.prizeType" @change="handleChange" placeholder="奖励类型" :disabled="dataForm.sort == 1 ? true : false">
          <el-option
            v-for="item in this.options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="积分数量:" prop="prizeRelation" label-width="100px" v-if="dataForm.prizeType == 1">
        <el-input type="text" placeholder="请输入整数" v-model.trim="dataForm.prizeRelation" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label= "选择物品" v-if="dataForm.prizeType == 2 || dataForm.prizeType == 3" label-width="100px">
        <el-button @click="addOrUpdateHandle" v-if="dataForm.prizeType == 2">赠卷</el-button>
        <el-button @click="addOrUpdateHandle" v-if="dataForm.prizeType == 3">选择商品</el-button>
        <el-table v-if="idList.length !== 0"
                  :data="infoList"
                  height="300"
                  border
                  style="width: 100%">
          <el-table-column
            prop="id"
            label="ID" v-if="this.infoList[0].id != null">
          </el-table-column>
          <el-table-column
            prop="img"
            label="商品图" v-if="this.infoList[0].img != null">
            <template slot-scope="scope">
              <el-popover
                placement="right"
                trigger="hover">
                <img :src="scope.row.img" style="max-height: 100px;"/>
                <img slot="reference" :src="scope.row.img" style="max-height: 50px;max-width: 130px">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsName"
            show-overflow-tooltip
            label="商品名" v-if="this.infoList[0].goodsName != null">
          </el-table-column>
          <!-- <el-table-column
            prop="address"
            label="价格类型">
            <template slot-scope="scope">
              {{scope.row.address === 1 ?'兑换商城':'福利商城'}}
            </template>
          </el-table-column> -->
          <el-table-column
            prop="goodsInventory"
            label="库存" v-if="this.infoList[0].goodsInventory != null">
          </el-table-column>

          <el-table-column
            prop="code"
            label="优惠卷编号" v-if="this.infoList[0].code != null">
          </el-table-column>
          <el-table-column
            prop="title"
            label="优惠卷名称" v-if="this.infoList[0].title != null">
          </el-table-column>
          <el-table-column
            prop="stock"
            label="库存" v-if="this.infoList[0].stock != null">
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small"  @click="deleteGoodsHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="奖励名称:" prop="prizeName" label-width="100px">
        <el-input type="text" placeholder="内容限制8字以内" v-model.trim="dataForm.prizeName" maxlength="8" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label="模板排序:" prop="sort" label-width="100px" >
        <el-input type="number" v-model.trim="dataForm.sort" placeholder="限制数字" style="width:120px" :disabled="dataForm.prizeNumber == -1 ? true : false"/>
      </el-form-item>
      <el-form-item label="获奖提示： " prop="prizeTip" label-width="100px">
        <el-input type="textarea" :rows="6" placeholder="获奖提示" v-model="dataForm.prizeTip" style="width:400px" />
      </el-form-item>
      <el-form-item label="中奖率： " prop="prizeProbability" label-width="100px">
        <div style="float: left">
          <el-input class="input1" name="project_type" type="text" :rows="6" placeholder="中奖率" v-model="dataForm.prizeProbability" :disabled="dataForm.sort == 1 ? true : false"/>
        </div>
        <div style="float: left;font-size: 30px;height: 40px;line-height: 40px; border: 1px solid #DCDFE6">%</div>
        <!--<input class="el-input__inner" type="text" placeholder="中奖率" v-model="dataForm.prizeProbability" :disabledext-="dataForm.prizeNumber === -1 ? true : false"/>-->
      </el-form-item>
      <el-form-item label="奖品数量： " prop="prizeNumber" label-width="100px" v-show="dataForm.prizeNumber != -1">
        <el-input type="text" :rows="6" placeholder="备注" v-model="dataForm.prizeNumber" style="width:400px" :disabled="dataForm.sort == 1 ? true : false"/>
      </el-form-item>

      <el-form-item label="图标" prop="imageUrl">
        <el-upload
          :class="{hide:hideUpload}"
          :action="this.$http.adornUrl(`/prize/uploadPrizeImg?path=${this.dataForm.prizePath}&token=${this.$cookie.get('token')}`)"
          :limit="1"
          list-type="picture-card"
          :file-list="dataForm.img"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :on-exceed="onExceed"
          style="margin-left: 20px; width: 200px; height: 150px">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
          <img width="100%" height="100px" :src="imageUrl" alt="">
        </el-dialog>
      </el-form-item>
    </el-form>
    <add-goods v-if="addGoodsVisible" ref="addGoods" @refsGetGoodsList="getGoodsList"></add-goods>
    <add-luck-draw v-if="addLuckDrawVisible" ref="addLuckDraw" @refsGetGoodsList="getGoodsList"></add-luck-draw>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false , clearValidate()">取消</el-button>
      <el-button type="primary" :disabled="this.flag" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import AddGoods from './activity-goods'
  import AddLuckDraw from './activity-luckdraw'
  export default {
    data () {
      var checkPrizeProbability = (rule, value, callback) => {
        debugger
        console.log(value)
        if (value.length === 0) {
          callback(this.$message.error('请输入中奖率'))
          return
        }
        let reg = /^(\d+)(.\d{0,5})?$/
        if (!reg.test(parseFloat(value))) {
          callback(this.$message.error('小数点后最多5位，请重新输入'))
          return
        }
        if (value > 100) {
          callback(this.$message.error('100或100以内浮点数，请重新输入'))
        }
        this.flag = false
      }
      var checkSort = (rule, value, callback) => {
        debugger
        if (value.length === 0) {
          callback(this.$message.error('排序不能为空'))
          return
        }
        let reg = /^[0-9]*[1-9][0-9]*$/
        if (!reg.test(value)) {
          callback(this.$message.error('类别排序为正整数'))
        }
        this.flag = false
      }
      var checkPrizeName = (rule, value, callback) => {
        debugger
        if (value.length === 0) {
          callback(this.$message.error('活动名称不能为空'))
          this.flag = false
        }
      }
      var checkPrizeNumber = (rule, value, callback) => {
        debugger
        if (value.length === 0) {
          callback(this.$message.error('请输入奖数品量'))
          this.flag = false
        }
      }
      return {
        flag: false,
        turnTableInfoId: 0,
        id: 0,
        subSortList: [],
        options: [
          {value: '1', label: '积分'},
          {value: '2', label: '抽奖赠券'},
          {value: '3', label: '商品'}
        ],
        addGoodsVisible: false,
        addLuckDrawVisible: false,
        dialogVisible: false,
        hideUpload: false,
        visible: false,
        idList: [],
        infoList: [],
        imageUrl: '',
        dataForm: {
          img: [],
          prizeType: '1',
          prizeRelation: '',
          prizeName: '',
          prizePath: 'prize',
          prizeImg: '',
          prizeTip: '',
          sort: '',
          prizeProbability: '',
          prizeNumber: ''
        },
        dataRule: {
          prizeName: [
             {validator: checkPrizeName, required: true, trigger: 'blur'}
          ],
          sort: [
             {validator: checkSort, required: true, trigger: 'blur'}
          ],
          prizeProbability: [
             {validator: checkPrizeProbability, required: true, trigger: 'blur'}
          ],
          prizeNumber: [
             {validator: checkPrizeNumber, required: true, trigger: 'blur'}
          ],
          prizeRelation: [
            { required: true, message: '积分数量不能为空', trigger: 'blur' }
          ],
          prizeTip: [
            { required: true, message: '请输入提示语句', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      AddGoods,
      AddLuckDraw
    },
    methods: {
      clearValidate () {
        this.$refs.dataForm.clearValidate()
      },
      handleChange () {
        this.idList = []
        this.infoList = []
      },
      addOrUpdateHandle () {
        this.idList = []
        this.infoList = []
        debugger
        if (this.dataForm.prizeType === '2') {
          this.addLuckDrawVisible = true
          this.$nextTick(() => {
            this.$refs.addLuckDraw.init()
          })
        }
        if (this.dataForm.prizeType === '3') {
          this.addGoodsVisible = true
          this.$nextTick(() => {
            this.$refs.addGoods.init(this.idList, this.infoList)
          })
        }
      },
      getGoodsList (idsGoods, subGoodsInfo) {
        this.idList = idsGoods
        this.infoList = subGoodsInfo
      },
      deleteGoodsHandle (id) {
        debugger
        this.idList.splice(this.idList.indexOf(id), 1)
        for (let i = 0; i < this.infoList.length; i++) {
          if (this.infoList[i].id === id) {
            this.infoList.splice(i, 1)
          }
        }
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
        if (!isJPG) {
          this.$message.error('上传图片只能是  JPG,PNG,GIF 格式！')
        }
      },
      // 图片预览
      handlePreview (file) {
        this.imageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= 1
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        debugger
        console.log(res.data)
        if (res.code === 0) {
          this.dataForm.img.push({name: 'activityImg', url: res.data})
          debugger
          console.log(this.dataForm.img)
        }
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= 1
        for (var i = 0; i < this.dataForm.img.length; i++) {
          var picc = this.dataForm.img[i]
          if (picc.url === file.url) {
            this.dataForm.img.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      init (turnTableId, PrizeId, sortList) {
        this.flag = false
        this.hideUpload = false
        debugger
        this.turnTableInfoId = turnTableId
        this.id = PrizeId
        this.subSortList = []
        this.idList = []
        this.infoList = []
        this.dataForm.img = []
        this.dataForm.prizeType = '1'
        this.dataForm.prizeRelation = ''
        this.dataForm.prizeNumber = ''
        this.dataForm.prizeName = ''
        this.dataForm.prizePath = 'prize'
        this.dataForm.prizeImg = ''
        this.dataForm.prizeTip = ''
        this.dataForm.sort = ''
        this.dataForm.prizeProbability = ''
        console.log(this.turnTableInfoId)
        this.$nextTick(() => {
          if (this.id) {
            this.$http({
              url: this.$http.adornUrl(`/prize/prizeInfoById/${this.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.id = data.data.id
                this.dataForm.prizeType = data.data.prizeType.toString()
                this.dataForm.prizeName = data.data.prizeName
                this.dataForm.sort = data.data.sort
                debugger
                for (var i = 0; i < sortList.length; i++) {
                  if (sortList[i] === data.data.sort) {
                    sortList.splice(i, 1)
                  }
                }
                this.subSortList = sortList
                console.log(this.subSortList)
                this.dataForm.prizeTip = data.data.prizeTip
                this.dataForm.prizeRelation = data.data.prizeRelation
                this.dataForm.prizeProbability = data.data.prizeProbability
                this.dataForm.prizeNumber = data.data.prizeNumber
                if (data.data.prizePath !== '' && data.data.prizeImg !== '') {
                  this.dataForm.img.push({name: 'activityImg', url: 'http://image.yilianbaihui.cn/consumer/' + data.data.prizePath + '/' + data.data.prizeImg})
                  this.hideUpload = true
                }
                // this.dataForm.imageUrl = 'http://image.yilianbaihui.cn/consumer/' + data.data.prizePath + data.data.prizeName}
                if (data.data.t != null && data.data.prizeType === 2) {
                  this.idList.push(data.data.t.id)
                  this.infoList.push({
                    'id': data.data.id,
                    'code': data.data.t.code,
                    'title': data.data.t.title,
                    'releaseType': data.data.t.releaseType,
                    'stock': data.data.t.stock
                  })
                }
                if (data.data.t != null && data.data.prizeType === 3) {
                  this.idList.push(data.data.t.id)
                  this.infoList.push({
                    'img': data.data.t.img,
                    'id': data.data.t.id,
                    'goodsName': data.data.t.name,
                    'priceType': data.data.t.priceType,
                    'goodsInventory': data.data.t.goodsInventory
                  })
                }
                console.log(data.data.T)
                console.log(data.data.prizePath)
                console.log(data.data.prizeImg)
                console.log(this.infoList)
                console.log(this.idList)
              }
            })
          }
          this.visible = true
        })
      },
      dataFormSubmit () {
        this.flag = true
        debugger
        if (this.dataForm.img.length > 0) {
          let index = this.dataForm.img[0].url.toString().lastIndexOf('\/')
          this.dataForm.prizeImg = this.dataForm.img[0].url.toString().substring(index + 1, this.dataForm.img[0].url.toString().length)
        } else if (!this.dataForm.img.length > 0) {
          this.flag = false
          return this.$message.error('请上传图标')
        }
        if (this.dataForm.prizeType === '2' || this.dataForm.prizeType === '3') {
          this.dataForm.prizeRelation = this.idList[0]
        }
        debugger
        for (var i = 0; i < this.subSortList.length; i++) {
          if (this.subSortList[i] === parseInt(this.dataForm.sort)) {
            this.flag = false
            return this.$message.error('排序有重复')
          }
        }
        if (this.dataForm.prizeRelation === '') {
          this.flag = false
          return this.$message.error('请输入积分数量')
        } else if (this.dataForm.sort === '') {
          this.flag = false
          return this.$message.error('排序不能为空')
        } else if (this.dataForm.prizeName === '') {
          this.flag = false
          return this.$message.error('请输入奖励名称')
        } else if (this.dataForm.prizeProbability === '') {
          this.flag = false
          return this.$message.error('请输入中奖率')
        } else if (this.dataForm.prizeProbability > 100) {
          this.flag = false
          debugger
          return this.$message.error('100或100以内浮点数，请重新输入')
        } else if (this.dataForm.prizeNumber === '') {
          this.flag = false
          return this.$message.error('请输入奖品数量')
        } else if (this.dataForm.prizeNumber < -1) {
          this.flag = false
          return this.$message.error('奖品数量应为正整数')
        }
        console.log(this.id)
        console.log(this.dataForm.prizeRelation)
        console.log(this.turnTableInfoId)
        this.$http({
          url: this.$http.adornUrl(`/prize/${!this.id ? 'addPrizeInfo' : 'modifyPrizeInfoById'}`),
          method: 'post',
          data: this.$http.adornData({
            'turnTableInfoId': this.turnTableInfoId,
            'id': this.id || undefined,
            'prizeType': this.dataForm.prizeType,
            'prizeRelation': this.dataForm.prizeRelation,
            'prizeName': this.dataForm.prizeName,
            'prizePath': this.dataForm.prizePath,
            'prizeImg': this.dataForm.prizeImg,
            'prizeTip': this.dataForm.prizeTip,
            'sort': this.dataForm.sort,
            'prizeNumber': this.dataForm.prizeNumber,
            'prizeProbability': this.dataForm.prizeProbability
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList', this.id)
              }
            })
          } else {
            this.$message.error(data.msg)
            this.flag = false
          }
        })
      }
    }
  }
</script>
<style>
  .input1 .el-input__inner{
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: 25px;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 2px;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    width: 130px;
    text-align: right;
    float: left;
  }
  .el-input {
    position: relative;
    font-size: 14px;
    display: inline-block;
    width: 60%;
  }
  .hide .el-upload--picture-card {  display: none; }
</style>
